package com.drcoffee.drcoffeemall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.drcoffee.drcoffeemall.entry.*;
import com.drcoffee.drcoffeemall.entry.search.OrderSearch;
import com.drcoffee.drcoffeemall.mapper.*;
import com.drcoffee.drcoffeemall.service.OrderService;
import com.drcoffee.drcoffeemall.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.redisson.api.RAtomicLong;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    final
    OrderMapper orderMapper;

    final
    UserMapper userMapper;

    final
    AddressMapper addressMapper;

    final
    PartsMapper partsMapper;

    final
    ShoppingCartMapper shoppingCartMapper;

    final
    AllPayVerifyUtil allPayVerifyUtil;

    private final Redisson redisson;   // 注入Redisson对象

    final
    RedisTemplate<String, Object> redisTemplate;

    final
    SendWxWorlUtil sendWxWorlUtil;
    private final EmailUtil emailUtil;

    final
    TradeMapper tradeMapper;

    final
    AfterSaleMapper afterSaleMapper;

    final
    GenerateCodeUtil generateCodeUtil;

    public OrderServiceImpl(SendWxWorlUtil sendWxWorlUtil, EmailUtil emailUtil, OrderMapper orderMapper, UserMapper userMapper, AddressMapper addressMapper, PartsMapper partsMapper, ShoppingCartMapper shoppingCartMapper, AllPayVerifyUtil allPayVerifyUtil, Redisson redisson, RedisTemplate<String, Object> redisTemplate, TradeMapper tradeMapper, AfterSaleMapper afterSaleMapper, GenerateCodeUtil generateCodeUtil) {
        this.sendWxWorlUtil = sendWxWorlUtil;
        this.emailUtil = emailUtil;
        this.orderMapper = orderMapper;
        this.userMapper = userMapper;
        this.addressMapper = addressMapper;
        this.partsMapper = partsMapper;
        this.shoppingCartMapper = shoppingCartMapper;
        this.allPayVerifyUtil = allPayVerifyUtil;
        this.redisson = redisson;
        this.redisTemplate = redisTemplate;
        this.tradeMapper = tradeMapper;
        this.afterSaleMapper = afterSaleMapper;
        this.generateCodeUtil = generateCodeUtil;
    }

    public User getUser(String Token) {
        return (User) redisTemplate.opsForValue().get(Token);
    }

    @Override
    public Result getAllOrder(OrderSearch orderSearch) {
        try {
            List<String> codes = new ArrayList<>();
            if (Objects.equals(orderSearch.getSearch(), "") || orderSearch.getSearch() == null) {
                // 不走模糊查询
                orderSearch.setCodes(codes);
            } else {
                // 走模糊查询
                orderSearch.setSearch("%" + orderSearch.getSearch() + "%");
                codes = orderMapper.getOrderCode(orderSearch.getSearch());
                orderSearch.setCodes(codes);
                // 模糊查询
                if (codes.isEmpty()) {
                    return new Result(1, "SUCCESS", "", null);
                }
            }
            PageHelper.startPage(orderSearch.getCurrPage(), orderSearch.getPageSize());
            List<Order> orderList = orderMapper.getAllOrder(orderSearch);
            // 批量查询所有订单的附件信息
            List<OrderAttachment> allOrderAttachments = orderMapper.getAllOrderAttachments(codes, orderSearch.getLanguage());

            Map<String, List<OrderAttachment>> attachmentMap = new HashMap<>();
            for (OrderAttachment attachment : allOrderAttachments) {
                String orderCode = attachment.getOrder_code();
                if (!attachmentMap.containsKey(orderCode)) {
                    attachmentMap.put(orderCode, new ArrayList<>());
                }
                attachmentMap.get(orderCode).add(attachment);
            }

            PageInfo<Order> orderPage = new PageInfo<>(orderList);
            for (Order order : orderPage.getList()) {
                List<OrderAttachment> orderAttachments = attachmentMap.get(order.getCode());
                order.setOrderAttachmentsList(orderAttachments);
            }
            return new Result(1, "SUCCESS", "", orderPage);
        } catch (Exception e) {
            log.error("===================== getAllOrder()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    @Override
    public Result submitOrder(String Token, Map<String, Object> orderMap) {
        RLock lock = redisson.getLock("order");
        try {
            lock.lock();// 加锁
            Order order = dataProcessing(Token, orderMap);
            User user = getUser(Token);
            orderMapper.submitOrder(order);
            orderMapper.submitOrderAttachment(order.getOrderAttachmentsList());
            List<String> part_codes = new ArrayList<>();
            for (OrderAttachment orderAttachment : order.getOrderAttachmentsList()) {
                part_codes.add(orderAttachment.getPart_code());
            }
            // 购物车下单后清除购物车
            boolean delCart = (boolean) orderMap.get("delCart");
            if (delCart) {
                shoppingCartMapper.deletePartByCode(user.getAccount(), part_codes);
            }
            // 发送提醒至企业微信用户
            if (user.getPermission_id() == 2) {
                sendWxWorlUtil.enSendAppoint(user.getBs_qw_user_id());
            }
            return new Result(1, "SUCCESS", "Order submitted successfully", order);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("===================== submitOrder()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        } finally {
            lock.unlock();//解锁
        }
    }

    /*
     * 发送订单信息至邮件
     * */
    @Override
    public Map<String, Object> sendOrderEmail(HttpServletResponse response, String Token, String order_code) {
        Map<String, Object> resultMap = new HashMap<>();
        User user = getUser(Token);
        try {
            Order order = orderMapper.getOrderAndPart(order_code, "EN");
            resultMap.put("order", order);
            File file = derivePdf(response, order_code, "EN", 2);
            emailUtil.sendEmailGo(3, order, user.getEmail(), "", file);
            emailUtil.sendEmailGo(5, order, user.getBs_user_email(), "", file);
        } catch (Exception e) {
            log.error("===================== sendOrderEmail()异常： =====================", e);
        }
        return resultMap;
    }

    @Override
    public File derivePdf(HttpServletResponse response, String order_code, String language, Integer type) throws IOException, JRException {
        // String filePath = "Leaf_Red.jasper";
        ServletOutputStream outputStream = response.getOutputStream();
        // 文件名
        String filename = "DrCoffee.pdf";
        // 设置两个头 一个是文件的打开方式 一个是mime类型
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
        response.setContentType("application/pdf");
        // 文件的输入流
        // InputStream inputStream = new FileInputStream(filePath);
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("pdf_template/Leaf_Red.jasper");
        // 2.创建JasperPrint,向jasper文件中填充数据
        Map<String, Object> parameters = new HashMap<>();

        // 查询所有数据
        Order allOrder = orderMapper.getOrderAndPart(order_code, language);
        List<OrderAttachment> orderPart = orderMapper.getOrderPart(order_code, language);
        allOrder.setOrderAttachmentsList(orderPart);

        List<Order> orders = new ArrayList<>();
        orders.add(allOrder);

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(orders, false);
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, dataSource);
        if (type == 1) {
            // 3.将JasperPrint已PDF的形式输出
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
            return null;
        } else {
            // Create a temporary file
            File file = File.createTempFile("DrCoffee", ".pdf");
            // Export the JasperPrint to the temporary file
            JasperExportManager.exportReportToPdfFile(jasperPrint, file.getAbsolutePath());
            return file;
        }
    }


    /* 查询物流信息 */
    @Override
    public Result getTransport(String order_code) {
        try {
            // 根据订单编号查询物流单号
            String transport_code = orderMapper.getTransportCodeByOrderCode(order_code);
            if (transport_code == null) {
                return new Result(2, "SUCCESS", "No waybill number", null);
            }
            HashMap<Object, Object> resultMap = new HashMap<>();
            JSONObject route = SfApiUtil.routeQuery(transport_code);
            JSONObject predict = SfApiUtil.estimatedDeliveryTime(transport_code);
            resultMap.put("route", route);
            resultMap.put("predict", predict);
            return new Result(1, "SUCCESS", "", resultMap);
        } catch (Exception e) {
            log.error("===================== getTransport异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    /* 根据code查询订单明细 */
    @Override
    public Result getOrderByCode(String Token, String code, String language) {
        try {
            User user = getUser(Token);
            // 查询订单
            Order order = orderMapper.getOrderByCode(code);

            if (order != null) {
                // 批量查询所有订单的附件信息
                List<String> codes = Collections.singletonList(code);
                List<OrderAttachment> allOrderAttachments = orderMapper.getAllOrderAttachments(codes, language);

                // 使用 Stream API来构建附件信息的映射
                Map<String, List<OrderAttachment>> attachmentMap = allOrderAttachments.stream()
                        .collect(Collectors.groupingBy(OrderAttachment::getOrder_code));

                // 设置订单的附件信息
                order.setOrderAttachmentsList(attachmentMap.get(order.getCode()));
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("order", order);
                if (user.getPermission_id() != 2) {
                    /* 查询售后信息 */
                    List<AfterSale> afterSaleList = afterSaleMapper.getAfterSaleListByOrder(order.getCode());
                    resultMap.put("afterSaleList", afterSaleList);
                }
                return new Result(1, "SUCCESS", "", resultMap);
            } else {
                return new Result(2, "SUCCESS", "未找到该订单", null);
            }
        } catch (Exception e) {
            log.error("===================== getOrderByCode()异常： =====================", e);
            return new Result(1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getNoPayOrderByCode(String code) {
        try {
            // 查询订单
            Order order = orderMapper.getOrderByCode(code);
            if (order == null) {
                // 未找到该订单
                return new Result(2, "SUCCESS", "", null);
            }

            // 查询该订单是否支付
            Integer tradeCount = orderMapper.getOrderTradeByCode(order.getCode());
            int orderStatus = order.getStatus();
            int payMethod = order.getPay_method();
            if (payMethod == 3 && orderStatus == 1) {
                // 该订单付款类型为线下转账，请尽快汇款并上传凭证。
                return new Result(4, "SUCCESS", "", null);
            } else if (tradeCount == 0 && orderStatus == 1 && payMethod == 0) {
                // 订单未支付且状态为1
                return new Result(1, "SUCCESS", "", order);
            } else if (tradeCount > 0 && orderStatus > 1) {
                // 订单已有支付记录
                return new Result(3, "SUCCESS", "", null);
            } else {
                // 其他情况
                return new Result(-1, "NULL", "", null);
            }
        } catch (Exception e) {
            log.error("===================== getNoPayOrderByCode()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result setOrderBackStatus(String code) {
        try {
            // 查询该订单是否支付
            Integer trade_count = orderMapper.getOrderTradeByCode(code);
            if (trade_count == 0) {
                // 设置为对公转账未上传凭证
                orderMapper.setPayMethod(code, 3);
                orderMapper.setBackStatus(code, 1);
                return new Result(1, "SUCCESS", "", null);
            } else {
                // 已存在该订单支付记录
                return new Result(2, "SUCCESS", "", null);
            }
        } catch (Exception e) {
            log.error("===================== setOrderBackStatus()异常： =====================", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }


    }

    @Override
    public Result getOrderHeader(String code) {
        try {
            Order order = orderMapper.getOrderByCode(code);
            return new Result(1, "SUCCESS", "", order);
        } catch (Exception e) {
            log.error("===================== getOrderHeader()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result addPayVoucher(PayVoucher payVoucher) {
        try {
            BigDecimal orderTotal = orderMapper.getOrderTotal(payVoucher.getOrder_code());
            payVoucher.setOrder_total(orderTotal);
            orderMapper.setBackStatus(payVoucher.getOrder_code(), 2);
            orderMapper.addPayVoucher(payVoucher);
            sendWxWorlUtil.sendAppoint(8);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== addPayVoucher()异常： =====================", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result sendRemit(String phone, String code) {
        try {
            Sample.sendPhoneCode(phone, code, "SMS_463622965");
            return new Result(1, "", "发送成功", null);
        } catch (Exception e) {
            log.error("===================== sendRemit()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getPayVoucher(String code) {
        try {
            String path = orderMapper.getPayVoucher(code);
            return new Result(1, "", "", path);
        } catch (Exception e) {
            log.error("===================== getPayVoucher()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getOrderPartsTotal(Map<String, Object> par) {
        try {
            String code = (String) par.get("code");
            List<String> partCodes = (List<String>) par.get("part_codes");
            List<BigDecimal> partsTotalList = orderMapper.getOrderAttachmentsByOrder(code, partCodes);
            // 使用Stream API计算总和
            BigDecimal totalSum = partsTotalList.stream()
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            return new Result(1, "", "", totalSum);
        } catch (Exception e) {
            log.error("===================== getOrderPartsTotal()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getPayType(String code) {
        try {
            Integer payType = orderMapper.getPayType(code);
            return new Result(1, "", "", payType);
        } catch (Exception e) {
            log.error("===================== getPayType()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    @Override
    public Result cancelOrder(String code) {
        try {
            Order order = orderMapper.getOrderByCode(code);
            // 查询订单状态
            if (order.getStatus() == 1) {
                // 未付款订单直接取消（状态为0）
                orderMapper.cancelOrder(code);
                return new Result(1, "SUCCESS", "", null);
            } else {
                // 无效操作
                return new Result(2, "Invalid operation", "", null);
            }
        } catch (Exception e) {
            log.error("===================== cancelOrder()异常： =====================", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result allPayVerify(String orderCode, Integer type) {
        return allPayVerifyUtil.payVerify(orderCode, type);
    }

    @Override
    public Result setOrderStatus(String orderCode, Integer status) {
        try {
            String status_time = "";
            if (status != 0) {
                status_time = ",status_time_0" + status;
            }
            orderMapper.setOrderStatus(orderCode, status, status_time);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== setOrderStatus()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    /**
     * 以下方法都用于处理订单数据
     */
    public Order dataProcessing(String Token, Map<String, Object> orderMap) {
        User user = getUser(Token);
        Order order = new Order();
        if (user != null) {
            // 根据地址id查询地址
            Address address = addressMapper.getAddressById((Integer) orderMap.get("address_id"));

            // 币种
            String currency = user.getPermission_id() == 2 ? "$" : "￥";
            order.setCurrency(currency); // 币种
            String code = orderCode(user.getPermission_id());
            order.setCode(code); // 订单编号
            order.setFirm_name(user.getFirm_name()); // 企业名称
            order.setRecipients(address.getRecipients()); // 收件人
            order.setPhone("(" + address.getArea_code() + ") " + address.getPhone()); // 联系电话
            // 设置收件地址
            order.setAddress(address.getAddress());
            if (user.getPermission_id() != 2) {
                order.setProvince(address.getProvince());
                order.setCity(address.getCity());
                order.setRegion(address.getRegion());
                order.setProvince_code(address.getProvince_code());
                order.setCity_code(address.getCity_code());
                order.setRegion_code(address.getRegion_code());
            }
            order.setRemark((String) orderMap.get("remark")); // 订单备注
            order.setUser_account(user.getAccount()); // 用户账号

            List<OrderAttachment> orderAttachmentList;
            List<Map<String, Object>> orderPartList = (List<Map<String, Object>>) orderMap.get("order_part");

            Map<String, Object> OrderPartsResultMap = handleOrderParts(order.getCode(), currency, orderPartList, user);
            order.setOrder_before_total((BigDecimal) OrderPartsResultMap.get("beforeTotal")); // 折前价格合计
            order.setOrder_total((BigDecimal) OrderPartsResultMap.get("total")); // 折后价格合计
            orderAttachmentList = (List<OrderAttachment>) OrderPartsResultMap.get("orderAttachmentList");

            // 一次判断：享受满送条件：国内企业用户 && 没有折扣
            if (user.getPermission_id() == 1 && (user.getDiscount_one().compareTo(BigDecimal.ZERO) == 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) == 0)) {
                // 二次判断：getGiveawayParts()方法中会筛出特价商品，不做特价商品的满送
                List<OrderAttachment> giveawayParts = getGiveawayParts(orderAttachmentList, (Integer) orderMap.get("type"), user.getErp_code(), user.getAccount());
                if (giveawayParts != null) {
                    orderAttachmentList.addAll(giveawayParts);
                }
            }
            if (user.getPermission_id() == 2) {
                // 海外用户跳过待付款状态
                order.setStatus(2);
                order.setStatus_time_02(new Date());
            } else {
                // 国内用户待付款状态
                order.setStatus(1);
            }

            order.setOrderAttachmentsList(orderAttachmentList); // 订单明细
        }
        return order;
    }


    public Map<String, Object> handleOrderParts(String order_code, String currency, List<Map<String, Object>> orderPartList, User user) {
        // 折前合计价格
        BigDecimal beforeTotal = new BigDecimal(0);

        // 折后合计价格
        BigDecimal total = new BigDecimal(0);
        List<OrderAttachment> orderAttachmentList = new ArrayList<>();

        // 判断该用户是否存在商品特殊价格
        List<SpecialPrice> specialPriceList = null;
        // 享受特价条件：国内企业用户 && 没有折扣
        if (user.getPermission_id() == 1 && (user.getDiscount_one().compareTo(BigDecimal.ZERO) == 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) == 0)) {
            specialPriceList = partsMapper.getSpecialPrice(user.getErp_code());
        }
        // 查询配件list By 订单配件编号
        // 提取所有订单配件编号
        List<String> initOrderPartCodes = orderPartList.stream()
                .map(map -> (String) map.get("part_code"))
                .toList();
        String language = user.getPermission_id() == 2 ? "EN" : "CN";
        List<Attachment> allOrderPartList = partsMapper.getPartsByCodes(PriceUtil.getPriceType("b", user.getPermission_id()), language, initOrderPartCodes);
        for (Map<String, Object> orderPart : orderPartList) {
            OrderAttachment orderAttachment = new OrderAttachment();
            orderAttachment.setOrder_code(order_code); // 订单编号
            orderAttachment.setPart_code((String) orderPart.get("part_code")); // 料号
            orderAttachment.setQuantity((Integer) orderPart.get("quantity")); // 数量
            orderAttachment.setCurrency(currency); // 币种
            orderAttachment.setIs_giveaway("N");
            /*
             * 处理价格
             * */
            // 查询配件（标准价格、折后价格）
            // 或者使用Stream API
            Optional<Attachment> parts = allOrderPartList.stream()
                    .filter(part -> part.getPart_code().equals(orderAttachment.getPart_code()))
                    .findFirst();
            Attachment attachment = parts.orElse(null);
            if (attachment == null) {
                throw new NullPointerException();
            }

//            Attachment attachment = partsMapper.getAttachmentByCode(PriceUtil.getPriceType("b", user.getPermission_id()), orderAttachment.getPart_code(), language);
            orderAttachment.setPrice(attachment.getPrice()); // 标准价格
            orderAttachment.setPacking(attachment.getPacking());
            orderAttachment.setUnit(attachment.getUnit());

            // 获取折后单价
            // BigDecimal bigDecimal = PriceUtil.calculateDiscountedPrice(orderAttachment.getPrice(), discountRate);// 折后价
            BigDecimal bigDecimal = DiscountedPriceUtil.getDiscountedPrice(orderAttachment.getPrice(), user);// 折后价
            orderAttachment.setSubtotal(bigDecimal); //折后单价
            attachment.setDiscounted_price(bigDecimal);

            // 判断存在特殊价格
            if (specialPriceList != null) {
                Optional<SpecialPrice> specialPrice = specialPriceList.stream()
                        .filter(special -> special.getPart_code().equals(attachment.getPart_code()))
                        .findFirst();
                specialPrice.ifPresent(special -> {
                            orderAttachment.setSubtotal(special.getPrice()); //折后单价
                            attachment.setDiscounted_price(special.getPrice());
                        }
                );
            }

            // 折前小计（标准价格*数量）
            BigDecimal beforePrice = orderAttachment.getPrice().multiply(BigDecimal.valueOf(orderAttachment.getQuantity()));
            orderAttachment.setBefore_total(beforePrice);
            beforeTotal = beforeTotal.add(beforePrice);


            // 折后小计（折后价格*数量）
            BigDecimal price = orderAttachment.getSubtotal().multiply(BigDecimal.valueOf(orderAttachment.getQuantity()));
            orderAttachment.setTotal(price);
            total = total.add(price);
            orderAttachmentList.add(orderAttachment);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("beforeTotal", beforeTotal);
        resultMap.put("total", total);
        resultMap.put("orderAttachmentList", orderAttachmentList);
        return resultMap;
    }


    public List<OrderAttachment> getGiveawayParts(List<OrderAttachment> orderAttachmentList, Integer type, String erp_code, String account) {
        // 订单配件料号list
        List<String> oarderPartCodes = orderAttachmentList.stream()
                .map(OrderAttachment::getPart_code)
                .collect(Collectors.toList());
        // 查询满足满赠条件的配件
        String source = type == 1 ? "t_cart" : "t_collect";
        // 查询出该用户参与特价的配件料号list
        List<String> init_specialPrice = partsMapper.getSpecialPricePartCodes(erp_code);
        // (筛出特价商品)-删除属于特价的配件料号
        oarderPartCodes.removeAll(init_specialPrice);
        // 查询满足满赠条件的配件
        List<Giveaway> satisfyGiveawayList = null;
        if (!oarderPartCodes.isEmpty()) {
            satisfyGiveawayList = partsMapper.getPartCodesBySatisfyGiveaway(account, source, oarderPartCodes);
        }
        if (satisfyGiveawayList == null || satisfyGiveawayList.isEmpty()) {
            // 没有参与满赠的配件
            return null;
        }
        List<OrderAttachment> giveawayPartList = new ArrayList<>();
        for (OrderAttachment orderPart : orderAttachmentList) {
            // Giveaway：满赠条件
            Giveaway targetGiveaway = satisfyGiveawayList.stream()
                    .filter(giveaway -> giveaway.getG_code().equals(orderPart.getPart_code()))
                    .findFirst()
                    .orElse(null);
            if (targetGiveaway != null && orderPart.getQuantity() >= targetGiveaway.getFull()) {
                OrderAttachment giveawayPart = new OrderAttachment();  // 创建新的对象
                giveawayPart.setOrder_code(orderPart.getOrder_code());
                giveawayPart.setPart_code(orderPart.getPart_code());
                giveawayPart.setPacking(orderPart.getPacking());
                giveawayPart.setUnit(orderPart.getUnit());
                giveawayPart.setQuantity(orderPart.getQuantity() / targetGiveaway.getFull() * targetGiveaway.getGift());
                giveawayPart.setCurrency(orderPart.getCurrency());
                giveawayPart.setPrice(BigDecimal.valueOf(0.00));
                giveawayPart.setSubtotal(BigDecimal.valueOf(0.00));
                giveawayPart.setBefore_total(BigDecimal.valueOf(0.00));
                giveawayPart.setTotal(BigDecimal.valueOf(0.00));
                giveawayPart.setIs_giveaway("Y");
                // 将设置好属性的对象添加到结果列表
                giveawayPartList.add(giveawayPart);
            }
        }
        return giveawayPartList;
    }

    // 生成编号
    private String orderCode(Integer permission_id) {
        RAtomicLong atomicLong = redisson.getAtomicLong("order_counter");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String PREFIX = "";
        if (permission_id == 0) { // 个人一类（个人账户零售价格）
            PREFIX = "PA";
        } else if (permission_id == 1) { // 国内企业（渠道价格）
            PREFIX = "PB";
        } else if (permission_id == 2) { // 海外（海外价格）
            PREFIX = "PC";
        } else if (permission_id == 3) { // 个人二类（企业账户零售价格）
            PREFIX = "PD";
        }
        String currentDate = sdf.format(new Date());
        String prefix_code = PREFIX + currentDate;
        long counter = atomicLong.incrementAndGet();
        String counterFormatted = String.format("%03d", counter + 1);
        prefix_code += counterFormatted;
        return prefix_code;
    }


}



